import React from "react";
import {inject, observer} from "mobx-react";
import Container from './Container';
import getUrlParams from '../../../../utils/getUrlParams';
import ThemeContext from "../theme";

const { Provider } = ThemeContext;

@inject('edcFormViewStore')
@observer
export default class FormViewPage extends React.Component {
  constructor(props) {
    super(props);

    this.store = props.edcFormViewStore;
  }

  componentWillUnmount () {
    const { reset } = this.store;

    if (window.fromRouter !== 'browser') {
      reset();
    }
  }

  componentDidMount () {
    const { location } = this.props;
    const { repairDate } = this.store;

    if (location.action && location.action === 'PUSH' && (!repairDate || window.fromRouter === 'browser')) {
      window.fromRouter = '';
      return;
    }
    this.init();
  }
  
  init = () => {
    const { repairDate } = this.store;
    const { code, data } = getUrlParams();
    const key = this.getKey(window.location.pathname) || this.getKey(window.location.hash);
  
    if (data && !repairDate) {
      this.store.initReadOnly(key, data);
    } else {
      Promise.all([
        this.store.initOauthKey(code)
      ]).then(() => { 
        this.store.init(key);
      });
    }
  }

  getKey(str) {
    const matches = str.match(/\/edc\/formview\/\w+/g);

    if (!matches) return;

    const key = matches[0].match(/\/[^\/]*?$/);

    return key && key[0].replace(/^\//, '');
  }

  render() {
    const { isInit } = this.store;

    return (
      !isInit ? <Container store={this.store}/> : null 
    );
  }
}